package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.hustcad.plm.pdm.common.service.entity.TyplmEntityBaseService;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.doc.dto.CreateDocInputDTO;
import com.hustcad.plm.pdm.doc.dto.SaveDocDTO;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocumentVO;
import com.hustcad.plm.pdm.file.model.dto.FileGroupDTO;
import com.hustcad.plm.pdm.flowbusiness.service.TyplmCheckCollectionObjService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.dto.BatchAddPartDescribeLinkDTO;
import com.hustcad.plm.pdm.partbom.enums.PartBomErrorCodeEnum;
import com.hustcad.plm.pdm.partbom.mapper.TyplmPartDescribeLinkMapper;
import com.hustcad.plm.pdm.partbom.service.TyplmPartDescribeLinkService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.type.mapper.TyplmTypeMapper;
import com.hustcad.plm.pdm.type.model.vo.TypeVueVO;
import com.hustcad.plm.pdm.type.service.TyplmAssociationConstraintService;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.ty.basic.common.ITyIterated;
import com.ty.basic.common.ITyLockable;
import com.ty.basic.common.ITyTyped;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.part.PartDescribeLinkDO;
import com.ty.basic.entity.part.PartMasterDO;
import com.ty.basic.entity.part.PartReferenceLinkDO;
import com.ty.basic.entity.type.TypeDO;
import com.ty.basic.exception.MessageException;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.util.StringUtil;
import com.ty.basic.utils.ArgumentUtils;
import com.ty.basic.utils.BatchQueryHelper;
import com.ty.basic.vo.ObjectHistoryRecordVO;
import cqrtplm.mapper.RTPartMapper;
import cqrtplm.service.RTDocService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class RTDocServiceImpl implements RTDocService {
    @Resource
    private TyplmDocumentService typlmDocumentService;

    @Resource
    private RTPartMapper rtPartMapper;

    @Resource
    private TyplmPdmPartService typlmPdmPartService;

    @Resource
    private TyplmTypeMapper typlmTypeMapper;

    @Resource
    private TyplmPartDescribeLinkService typlmPartDescribeLinkService;

    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Resource
    private TyplmCheckCollectionObjService typlmCheckCollectionObjService;

    @Resource
    private TyplmAssociationConstraintService typlmAssociationConstraintService;

    @Resource
    private TyplmPartDescribeLinkMapper typlmPartDescribeLinkMapper;

    @Resource
    private TyplmEntityBaseService typlmEntityBaseService;

    @Resource
    private TyplmTypeService typlmTypeService;

    @Resource
    private TyplmPartService typlmPartService;


    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public DocumentVO createDocument(FileGroupDTO fileGroupDto, CreateDocInputDTO createDocInputDTO, Map<String, List<String>> maps) {
        SaveDocDTO saveDocDto = new SaveDocDTO();
        saveDocDto.setCreateDocInputDTO(createDocInputDTO);
        saveDocDto.setIbaAttribute(maps);
        saveDocDto.setFileGroupDto(fileGroupDto);
        return typlmDocumentService.insertDoc(saveDocDto);
    }

    @Override
    public void batchPartDescribeAndReferenceLink(DocumentVO docVo, List<String> list){
        String type = docVo.getDoctype();
        boolean mark = false;
        BigInteger typeOid = docVo.getTypeoid();
        List<TypeVueVO> typeVueVOS = typlmTypeService.queryAccessType(Collections.singletonList(typeOid));
        String inthId = typeVueVOS.get(0).getInthid();
        if(inthId.contains("DesignDrawings")){
            mark = true;
        }
        String oidStr = docVo.getOid();
        if (StringUtil.isNotEmpty(oidStr) && oidStr.contains(":")) {
            oidStr = oidStr.split(":")[1];
        }
        List<PartReferenceLinkDO> objLst = new ArrayList<>();  // 参考关系
        List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTO = new ArrayList<>();  // 描述关系
        Set<String> typeOtypes = new HashSet<>();
        typeOtypes.add(TableTypeConstrant.TY_PART_REFERENCE_LINK_OTYPE);
        List<TypeDO> typeDOS = BatchQueryHelper.queryExampleColumnIn(typeOtypes, TypeDO.class, "logicalidentifier", this.typlmTypeMapper);
        Map<String, BigInteger> typeOidMap = typeDOS.stream().collect(
                Collectors.toMap(TypeDO::getLogicalidentifier, TypeDO::getOid));


        if (CollUtil.isNotEmpty(list)) {
            String[] split = list.get(0).split(";");

            for (String item : split) {
                String partNumber = item.split(",")[0];
                PartDO partDO = rtPartMapper.queryLatestPartByNumberAndView(partNumber, "Design", "RELEASED");//查询已发布版本
                if(partDO == null){
                    partDO = rtPartMapper.queryLatestPartByNumberAndView(partNumber, "Design", "EffectiveNot"); // 查询已生效未出图版本
                }
                if(partDO == null){
                    continue;
                }
                if ("ty.inteplm.part.CTyPart|PatternCode".equals(partDO.getTypeotype())) {
                    processPatternCodeParts(partNumber, docVo, oidStr, typeOidMap, objLst, batchAddPartDescribeLinkDTO);
                } else {
                    List<ObjectHistoryRecordVO> partLists = typlmPartService.queryPartByNumberAndView(partNumber, "Design",false);
                    for(ObjectHistoryRecordVO objectHistoryRecordVO : partLists){
                        String oid = objectHistoryRecordVO.getOid();
                        if (StringUtil.isNotEmpty(oid) && oid.contains(":")) {
                            oid = oid.split(":")[1];
                        }
                        if(oid.equals(partDO.getOid().toString())){
                            createPartReferenceLink(partDO.getOid(), docVo, typeOidMap, objLst);
                            createPartDescribeLink(partDO.getOid(), oidStr, batchAddPartDescribeLinkDTO);
                            break;
                        }else {
                            createPartReferenceLink(new BigInteger(oid), docVo, typeOidMap, objLst);
                            createPartDescribeLink(new BigInteger(oid), oidStr, batchAddPartDescribeLinkDTO);
                        }
                    }
                }
            }
        }

        // 执行批量操作
        if (mark) {
            batchAddPartDescribeLink(batchAddPartDescribeLinkDTO);
        } else {
            typlmPdmPartService.batchInsertPartReferenceLink(objLst, true);
        }
    }

    // 提取的方法：处理PatternCode类型的部件
    private void processPatternCodeParts(String partNumber, DocumentVO docVo, String oidStr,
                                         Map<String, BigInteger> typeOidMap,
                                         List<PartReferenceLinkDO> objLst,
                                         List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTO) {
        List<PartDO> partDO1S = rtPartMapper.queryLatestMaterialByViewAndViewState(partNumber + "%", "Design", "RELEASED");
        List<PartDO> partDO2S = rtPartMapper.queryLatestMaterialByViewAndViewState(partNumber + "%", "Design", "EffectiveNot");
        List<PartDO> partDOS = new ArrayList<>();
        if(CollUtil.isNotEmpty(partDO1S)){
            partDOS.addAll(partDO1S);
        }
        if(CollUtil.isNotEmpty(partDO2S)){
            partDOS.addAll(partDO2S);
        }
        Map<String,String> map = new HashMap<>();
        List<BigInteger> masterOids = new ArrayList<>();
        for(PartDO partDO : partDOS){
            BigInteger masteredoid = partDO.getMasteredoid();
            masterOids.add(masteredoid);
            map.put(partDO.getOid().toString(), partDO.getMasteredoid().toString());
        }
        List<PartMasterDO> partMasterDOS = typlmPartService.queryPartMasterByMasterIds(masterOids);
        Map<String,String> partNumberMap = new HashMap<>();
        for(PartMasterDO partMasterDO : partMasterDOS){
            partNumberMap.put(partMasterDO.getOid().toString(), partMasterDO.getPartnumber());
        }
        for (PartDO childPartDO : partDOS) {
            String s = map.get(childPartDO.getOid().toString());
            List<ObjectHistoryRecordVO> partLists = typlmPartService.queryPartByNumberAndView(partNumberMap.get(s), "Design",false);
            for(ObjectHistoryRecordVO objectHistoryRecordVO : partLists){
                String oid = objectHistoryRecordVO.getOid();
                if (StringUtil.isNotEmpty(oid) && oid.contains(":")) {
                    oid = oid.split(":")[1];
                }
                if(oid.equals(childPartDO.getOid().toString())){
                    createPartReferenceLink(childPartDO.getOid(), docVo, typeOidMap, objLst);
                    createPartDescribeLink(childPartDO.getOid(), oidStr, batchAddPartDescribeLinkDTO);
                    break;
                }else {
                    createPartReferenceLink(new BigInteger(oid), docVo, typeOidMap, objLst);
                    createPartDescribeLink(new BigInteger(oid), oidStr, batchAddPartDescribeLinkDTO);
                }
            }
        }
    }

    /**
     * 构建参考文档关系
     * @return $RETURN$
     * @author dinglonghao
     * @date 2025/10/11$ 下午11:16$
     */
    private void createPartReferenceLink(BigInteger partOid, DocumentVO documentVO,
                                         Map<String, BigInteger> typeOidMap,
                                         List<PartReferenceLinkDO> objLst) {
        // 创建 PartReferenceLinkDO
        PartReferenceLinkDO pDO = new PartReferenceLinkDO();
        pDO.setAoid(partOid);
        pDO.setAotype(TableTypeConstrant.TY_PART_OTYPE);
        pDO.setBoid(new BigInteger(documentVO.getMasteredoid()));
        pDO.setBotype(documentVO.getMasteredotype());
        pDO.setOid(this.snowflakeIdComponent.getInstance().nextId());
        pDO.setTypeotype(TableTypeConstrant.TY_PART_REFERENCE_LINK_OTYPE);
        pDO.setTypeoid(typeOidMap.get(pDO.getTypeotype()));
        pDO.setName(documentVO.getName());
        objLst.add(pDO);
    }

    /**
     * 构建描述文档关系
     * @param partOid
     * @param oidStr
     * @param batchAddPartDescribeLinkDTO
     * @return oidStr
     * @author dinglonghao
     * @date 2025/10/11$ 下午11:14$
     */
    private void createPartDescribeLink(BigInteger partOid, String oidStr,
                                         List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTO) {
        // 创建 PartDescribeLinkDTO
        BatchAddPartDescribeLinkDTO partDescribeLinkDTO = new BatchAddPartDescribeLinkDTO();
        partDescribeLinkDTO.setOid(partOid);
        partDescribeLinkDTO.setOtype(TableTypeConstrant.TY_PART_OTYPE);
        List<IdentifierEntity> refObjList = new ArrayList<>();
        refObjList.add(new IdentifierEntity(new BigInteger(oidStr), TableTypeConstrant.TY_DOC_OTYPE));
        partDescribeLinkDTO.setRefObj(refObjList);
        batchAddPartDescribeLinkDTO.add(partDescribeLinkDTO);
    }




    public void batchAddPartDescribeLink(List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTOList) {
        // 参数校验并获取实体映射
        Map<BigInteger, CTyEntityBaseDO> entityMap = judgeAddOrDeletePartDescribeLinkParam(batchAddPartDescribeLinkDTOList, false);
        List<PartDescribeLinkDO> partDescribeLinkDOS = new LinkedList<>();

        // 按otype分组处理
        batchAddPartDescribeLinkDTOList.stream()
                .collect(Collectors.groupingBy(BatchAddPartDescribeLinkDTO::getOtype))
                .forEach((otype, list) -> {
                    list.forEach(batchAddPartDescribeLinkDTO -> {
                        // 处理部件到文档的链接
                        if ("ty.inteplm.part.CTyPart".equalsIgnoreCase(otype)) {
                            processPartToDocLinks(batchAddPartDescribeLinkDTO, entityMap, partDescribeLinkDOS);
                        }
                        // 处理文档到部件的链接
                        else if ("ty.inteplm.doc.CTyDoc".equalsIgnoreCase(otype)) {
                            processDocToPartLinks(batchAddPartDescribeLinkDTO, entityMap, partDescribeLinkDOS);
                        }
                    });
                });

        // 如果有需要添加的链接
        if (CollUtil.isNotEmpty(partDescribeLinkDOS)) {
            // 去重处理
            ConcurrentSkipListMap<String, PartDescribeLinkDO> uniqueLinks = partDescribeLinkDOS.parallelStream()
                    .collect(Collectors.toMap(
                            o -> o.getAoid() + "," + o.getBoid(),
                            Function.identity(),
                            (oldObj, newObj) -> oldObj,
                            ConcurrentSkipListMap::new
                    ));

            // 查询已存在的链接
            List<PartDescribeLinkDO> exsitLinkDOList = typlmPartDescribeLinkMapper
                    .batchQueryPartDescribeLinkByAoidBoid(new ArrayList<>(uniqueLinks.values()));

            if (CollUtil.isNotEmpty(exsitLinkDOList)) {
                // 构建错误信息
                List<MessageException> errs = buildExistingLinkErrors(exsitLinkDOList);
                throw new MessageException(errs.stream().distinct().collect(Collectors.toList()));
            }

            // 批量插入
            typlmEntityBaseService.batchInsertWithCommit(uniqueLinks.values());
        }
    }

    // 处理部件到文档的链接
    private void processPartToDocLinks(BatchAddPartDescribeLinkDTO dto,
                                       Map<BigInteger, CTyEntityBaseDO> entityMap,
                                       List<PartDescribeLinkDO> result) {
        dto.getRefObj().stream()
                .filter(vo -> "ty.inteplm.doc.CTyDoc".equalsIgnoreCase(vo.getOtype()))
                .forEach(vo -> {
                    // 添加主链接
                    result.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(
                            dto.getOid(), dto.getOtype(), vo.getOid(), vo.getOtype()));

                    // 如果是工作版本，添加源迭代链接
                    CTyEntityBaseDO entity = entityMap.get(vo.getOid());
                    if (entity instanceof ITyLockable && "wrk".equalsIgnoreCase(((ITyLockable)entity).getLockstateinfo())) {
                        result.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(
                                dto.getOid(), dto.getOtype(),
                                ((ITyIterated)entity).getSourceiterationoid(),
                                entity.getOtype()));
                    }
                });
    }

    // 处理文档到部件的链接
    private void processDocToPartLinks(BatchAddPartDescribeLinkDTO dto,
                                       Map<BigInteger, CTyEntityBaseDO> entityMap,
                                       List<PartDescribeLinkDO> result) {
        dto.getRefObj().stream()
                .filter(vo -> "ty.inteplm.part.CTyPart".equalsIgnoreCase(vo.getOtype()))
                .forEach(vo -> {
                    // 添加主链接
                    result.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(
                            vo.getOid(), vo.getOtype(), dto.getOid(), dto.getOtype()));

                    // 如果是工作版本，添加源迭代链接
                    CTyEntityBaseDO entity = entityMap.get(vo.getOid());
                    if (entity instanceof ITyLockable && "wrk".equalsIgnoreCase(((ITyLockable)entity).getLockstateinfo())) {
                        result.add(typlmPartDescribeLinkService.getPartDescribeLinkDO(
                                ((ITyIterated)entity).getSourceiterationoid(),
                                entity.getOtype(),
                                dto.getOid(),
                                dto.getOtype()));
                    }
                });
    }

    // 构建已存在链接的错误信息
    private List<MessageException> buildExistingLinkErrors(List<PartDescribeLinkDO> existingLinks) {
        // 收集相关实体
        List<CTyEntityBaseDO> relatedEntities = existingLinks.stream()
                .flatMap(link -> Stream.of(
                        new CTyEntityBaseDO(link.getAoid(), link.getAotype()),
                        new CTyEntityBaseDO(link.getBoid(), link.getBotype())
                ))
                .distinct()
                .collect(Collectors.toList());

        // 获取实体显示名称
        Map<String, String> entityDisplayNames = CommonUtil.getEntityDisplayNameList(relatedEntities);

        // 构建错误列表
        return existingLinks.stream()
                .map(link -> PartBomErrorCodeEnum.PARTDESCRIBELINK_ALREADY_EXSITS.getException(
                        new Object[]{
                                entityDisplayNames.getOrDefault("ty.inteplm.part.CTyPart:" + link.getAoid(), String.valueOf(link.getAoid())),
                                entityDisplayNames.getOrDefault("ty.inteplm.doc.CTyDoc:" + link.getBoid(), String.valueOf(link.getBoid()))
                        }))
                .collect(Collectors.toList());
    }

    private Map<BigInteger, CTyEntityBaseDO> judgeAddOrDeletePartDescribeLinkParam(List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTOList, boolean isDelete) {
        // 参数校验
        ArgumentUtils.checkArgumentNull(batchAddPartDescribeLinkDTOList, "batchAddPartDescribeLinkDTO");
        batchAddPartDescribeLinkDTOList.forEach(vo -> {
            ArgumentUtils.checkArgumentNull(vo.getOid(), "batchAddPartDescribeLinkDTO.oid");
            ArgumentUtils.checkArgumentNull(vo.getOtype(), "batchAddPartDescribeLinkDTO.otype");
            ArgumentUtils.checkArgumentNull(vo.getRefObj(), "batchAddPartDescribeLinkDTO.refObjOid");
        });

        // 收集所有需要查询的实体
        List<CTyEntityBaseDO> entityBaseDOS = new ArrayList<>();
        batchAddPartDescribeLinkDTOList.stream()
                .flatMap(vo -> Stream.concat(
                        Stream.of(vo),
                        vo.getRefObj().stream().map(ref -> new BatchAddPartDescribeLinkDTO(ref.getOid(), ref.getOtype(), null))
                ))
                .collect(Collectors.groupingBy(
                        BatchAddPartDescribeLinkDTO::getOtype,
                        Collectors.mapping(BatchAddPartDescribeLinkDTO::getOid, Collectors.toList())
                ))
                .forEach((otype, oidList) -> entityBaseDOS.addAll(CommonUtil.batchQueryEntityList(oidList, otype)));

//        // 检查版本状态
//        if (!isDelete) {
//            typlmCheckCollectionObjService.checkCollectObjMajorAndLatestVersion(entityBaseDOS);
//        }

        // 添加工作版本实体
        addWrkEntity(batchAddPartDescribeLinkDTOList, entityBaseDOS);

        // 查询类型信息
        Map<BigInteger, TypeVueVO> typeDOMap = entityBaseDOS.stream()
                .filter(ITyTyped.class::isInstance)
                .map(vo -> ((ITyTyped)vo).getTypeoid())
                .collect(Collectors.toList())
                .stream()
                .collect(Collectors.toMap(
                        Function.identity(),
                        oid -> typlmTypeService.queryTypeByIds(Collections.singletonList(oid)).get(0),
                        (k1, k2) -> k1
                ));

        // 构建实体映射并验证业务规则
        Map<BigInteger, CTyEntityBaseDO> entityMap = entityBaseDOS.stream()
                .collect(Collectors.toMap(CTyEntityBaseDO::getOid, Function.identity(), (k1, k2) -> k1));

        List<MessageException> errs = new ArrayList<>();

        batchAddPartDescribeLinkDTOList.forEach(batchAddPartDescribeLinkDTO -> {
            // 检查主实体是否存在
            if (!entityMap.containsKey(batchAddPartDescribeLinkDTO.getOid())) {
                errs.add(SystemErrorCodeEnum.BIZ_OBJECT_NOT_FOUND.getException(new Object[]{batchAddPartDescribeLinkDTO.getOid()}));
            } else {
                CTyEntityBaseDO cTyEntityBaseDO = entityMap.get(batchAddPartDescribeLinkDTO.getOid());
                // 检查工作版本状态
                //                if (cTyEntityBaseDO instanceof ITyLockable && !"wrk".equalsIgnoreCase(((ITyLockable)cTyEntityBaseDO).getLockstateinfo())) {
                //                    errs.add(ConfiguredBomErrorCodeEnum.CONFIGUREDBOM_OBJECT_NOT_WRK.getException(
                //                            new Object[]{CommonUtil.getEntityDisplayName(cTyEntityBaseDO)}));
                //                }

                // 检查部件类型约束
                if ("ty.inteplm.part.CTyPart".equalsIgnoreCase(batchAddPartDescribeLinkDTO.getOtype()) && !isDelete) {
                    checkPartTypeConstraints(batchAddPartDescribeLinkDTO, cTyEntityBaseDO, typeDOMap, entityMap, errs);
                }
            }

            // 检查引用实体是否存在
            batchAddPartDescribeLinkDTO.getRefObj().forEach(vo -> {
                if (!entityMap.containsKey(vo.getOid())) {
                    errs.add(SystemErrorCodeEnum.BIZ_OBJECT_NOT_FOUND.getException(new Object[]{vo.getOid()}));
                }
            });
        });

        if (CollUtil.isNotEmpty(errs)) {
            throw new MessageException(errs);
        }

        return entityMap;
    }

    // 检查部件类型约束
    private void checkPartTypeConstraints(BatchAddPartDescribeLinkDTO dto,
                                          CTyEntityBaseDO entity,
                                          Map<BigInteger, TypeVueVO> typeDOMap,
                                          Map<BigInteger, CTyEntityBaseDO> entityMap,
                                          List<MessageException> errs) {
        PartDO partDO = (PartDO)entity;
        TypeVueVO typeVueVO = typeDOMap.get(partDO.getTypeoid());
        List<String> allowInthidList = typlmAssociationConstraintService
                .queryTypeInthidByLinkAndAType("ty.inteplm.part.CTyPartDescribeLink", typeVueVO.getInthid());

        Map<String, String> errMap = new HashMap<>();

        dto.getRefObj().forEach(vo -> {
            CTyEntityBaseDO doc = entityMap.get(vo.getOid());
            TypeVueVO docType = typeDOMap.get(((ITyTyped)doc).getTypeoid());

            if (!ObjectUtils.isNotEmpty(allowInthidList) ||
                    allowInthidList.stream().noneMatch(item ->
                                                               docType.getInthid().equals(item) || docType.getInthid().startsWith(item + "|"))) {

                errMap.merge(
                        typeVueVO.getDisplayName(),
                        docType.getDisplayName(),
                        (existing, newValue) -> existing.contains(newValue) ? existing : existing + ", " + newValue
                );
            }
        });

        errMap.forEach((key, value) -> {
            errs.add(PartBomErrorCodeEnum.TYPE_CAN_NOT_ADD_PARTDESCRIBELINK.getException(new Object[]{key, value}));
        });
    }

    private void addWrkEntity(List<BatchAddPartDescribeLinkDTO> batchAddPartDescribeLinkDTOList, List<CTyEntityBaseDO> entityBaseDOS) {
        // 获取所有工作版本的源迭代OID
        List<BigInteger> coOids = entityBaseDOS.stream()
                .filter(vo -> vo instanceof ITyLockable && "wrk".equalsIgnoreCase(((ITyLockable)vo).getLockstateinfo()))
                .map(vo -> ((ITyIterated)vo).getSourceiterationoid())
                .collect(Collectors.toList());

        // 获取没有工作版本的CO实体
        List<CTyEntityBaseDO> noWrkCoEntityList = entityBaseDOS.stream()
                .filter(vo -> vo instanceof ITyLockable && "c/o".equalsIgnoreCase(((ITyLockable)vo).getLockstateinfo()))
                .filter(s -> !coOids.contains(s.getOid()))
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(noWrkCoEntityList)) {
            return;
        }

        // 按类型分组查询工作版本
        List<CTyEntityBaseDO> wrkCtyEntityList = new ArrayList<>();
        noWrkCoEntityList.stream()
                .collect(Collectors.groupingBy(CTyEntityBaseDO::getOtype, Collectors.mapping(CTyEntityBaseDO::getOid, Collectors.toList())))
                .forEach((key, value) -> wrkCtyEntityList.addAll(CommonUtil.getWrkByCoIds(key, value)));

        // 构建CO到工作版本的映射
        Map<BigInteger, CTyEntityBaseDO> coWrkMap = wrkCtyEntityList.stream()
                .filter(ITyLockable.class::isInstance)
                .collect(Collectors.toMap(
                        vo -> ((ITyIterated)vo).getSourceiterationoid(),
                        Function.identity(),
                        (k1, k2) -> k1
                ));

        // 更新DTO中的引用对象
        List<BigInteger> noWrkCoOids = noWrkCoEntityList.stream()
                .map(CTyEntityBaseDO::getOid)
                .collect(Collectors.toList());

        batchAddPartDescribeLinkDTOList.forEach(batchAddPartDescribeLinkDTO -> {
            List<IdentifierEntity> refObj = batchAddPartDescribeLinkDTO.getRefObj();
            refObj.stream()
                    .map(IdentifierEntity::getOid)
                    .filter(noWrkCoOids::contains)
                    .forEach(bigInteger -> {
                        CTyEntityBaseDO cTyEntityBaseDO = coWrkMap.get(bigInteger);
                        refObj.add(new IdentifierEntity(cTyEntityBaseDO.getOid(), cTyEntityBaseDO.getOtype()));
                    });
        });

        entityBaseDOS.addAll(wrkCtyEntityList);
    }




}
